<!--
 * @Author: [kangjie]
 * @Date: 2022-04-20 14:58:13
 * @LastEditors: [kangjie]
 * @LastEditTime: 2022-04-21 13:07:19
 * @Description:
-->
<template>
  <!-- 所有菜品管理 -->
  <div class="product">
    <!-- 第一行开始 查询功能 -->
    <div class="header">
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-form-item>
          <el-button type="primary" @click="toAdd">添加菜品</el-button>
        </el-form-item>
        <el-form-item label="菜名">
          <el-input v-model="form.name" placeholder="请输入菜名" clearable />
        </el-form-item>
        <el-form-item label="菜品状态">
          <el-select
            v-model="form.status"
            placeholder="请输入菜品状态"
            clearable
          >
            <el-option label="正常" value="正常" />
            <el-option label="下架" value="下架" />
          </el-select>
        </el-form-item>
        <el-form-item label="菜品类别">
          <el-select
            v-model="form.productCategoryId"
            placeholder="请选择菜品类别"
            clearable
          >
            <el-option
              v-for="item in category"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 第一行结束 -->
    <!-- 第二行开始 显示所有菜品数据 -->
    <div class="center">
      <el-table :data="productData" style="width: 100%">
        <el-table-column label="序号" type="index" :index="1" align="center" />
        <el-table-column
          prop="id"
          label="菜品编号"
          width="180"
          align="center"
        />
        <el-table-column
          prop="name"
          label="菜品名称"
          width="180"
          align="center"
        />
        <el-table-column prop="photo" label="图片" width="160" align="center">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="right">
              <img slot="reference" :src="scope.row.photo" alt="图片加载失败" />
              <img
                :src="scope.row.photo"
                alt="图片加载失败"
                style="width: 200px"
              />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="180" align="center" />
        <el-table-column prop="status" label="状态" width="180" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == '正常'" type="success"
              >正常</el-tag
            >
            <el-tag v-else type="danger">下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="category.name"
          label="菜品分类"
          width="180"
          align="center"
        />
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-tag type="success" class="edit" @click="toEdit(scope.row)"
              >编辑</el-tag
            >
            <el-tag
              v-if="scope.row.status === '正常'"
              type="danger"
              class="outline"
              @click="outLine(scope.row.id)"
              >下架</el-tag
            >
            <el-tag
              v-else
              type="warning"
              class="online"
              @click="onLine(scope.row.id)"
              >上架</el-tag
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 第二行结束 -->
    <!-- 第三行开始 底部分页 -->
    <div class="footer">
      <el-pagination
        :current-page="form.page"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="form.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 第三行结束 -->

    <!-- 模态框 -->
    <el-dialog :title="title" :visible.sync="visible" @close="toClose">
      <el-form ref="modelForm" :model="sform" :rules="rules">
        <el-form-item
          label="菜品名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="sform.name" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item
          label="菜品类别"
          :label-width="formLabelWidth"
          prop="productCategoryId"
        >
          <el-select
            v-model="sform.productCategoryId"
            placeholder="请选择菜品类别"
            clearable
          >
            <el-option
              v-for="item in category"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
          <el-input v-model.number="sform.price" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item label="封面" :label-width="formLabelWidth" prop="photo">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="sform.photo" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-form-item label="菜品介绍" :label-width="formLabelWidth">
          <el-input v-model="sform.description" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="toSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入查询所有菜品分类的方法
import { pageQuery } from "@/api/proCategory";
import { pageQueryPro, saveOrUpdate, offline, online } from "@/api/product";
// 引入图片上传接口
import { uploadFileURL } from "@/utils/config";

export default {
  data() {
    return {
      // 菜品查询条件表单
      form: {
        page: 1,
        pageSize: 10,
      },
      // 分类查询条件表单
      catParams: {
        page: 1,
        pageSize: 100,
      },
      // 添加或更新专用表单
      sform: {},
      // 所有分类数据
      category: [],
      // 所有菜品数据存放
      productData: [],
      // 菜品总条数
      total: 0,
      // 控制模态框的显示与隐藏
      visible: false,
      // 控制模态框标题的显示信息
      title: "",
      // 控制模态中每一个表单元素的长度
      formLabelWidth: "120px",
      // 图片上传的路径
      uploadFileURL,
      imageUrl: "",
      // 表单验证
      rules: {
        name: [{ required: true, message: "请输入菜品名称", trigger: "blur" }],
        productCategoryId: [
          { required: true, message: "请选择菜品类别", trigger: "change" },
        ],
        price: [
          {
            required: true,
            message: "请输入数字价格",
            trigger: "blur",
            type: "number",
          },
        ],
        photo: [{ required: true, message: "请选择封面", trigger: "change" }],
      },
    };
  },
  created() {
    // 在一开始的时候，就直接获取菜品分类了
    this.getAllCategory();
    // 分页查询菜品
    this.getAllProduct();
  },
  methods: {
    // 图片上传成功的方法
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.sform.photo = res.data;
    },
    // 图片上传之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 提交查询
    onSubmit() {
      for (const i in this.form) {
        if (!this.form[i]) {
          delete this.form[i];
        }
      }
      this.getAllProduct();
    },
    // 获取所有菜品分类
    async getAllCategory() {
      const res = await pageQuery(this.catParams);
      this.category = res.data.list;
    },
    // 分页查询所有菜品信息
    async getAllProduct() {
      const res = await pageQueryPro(this.form);
      this.productData = res.data.list;
      this.total = res.data.total;
    },
    // 当前的菜品条数发生变化时触发
    handleSizeChange(pageSize) {
      // 每次改变size，默认跳转到第一页
      this.form.page = 1;
      this.form.pageSize = pageSize;
      // 重新请求数据
      this.getAllProduct();
    },
    // 当前的页面页码发生变化时触发
    handleCurrentChange(page) {
      this.form.page = page;
      // 重新请求数据
      this.getAllProduct();
    },
    // 处理添加菜品的方法
    toAdd() {
      // 显示模态框
      this.visible = true;
      // 修改模态框头部显示
      this.title = "添加菜品";
      // 让imgUrl为空，让上传图片的控件显示出来
      this.imageUrl = "";
    },
    // 编辑
    toEdit(row) {
      this.sform = row;
      // 显示模态框
      this.visible = true;
      // 修改模态框标题
      this.title = "编辑菜品";
      // 让imageUrl不为空，让图片显示出来
      this.imageUrl = "123";
    },
    // 关闭模态框触发事件
    toClose() {
      // 清空表单
      this.sform = {};
      // 清空表单验证
      this.$refs.modelForm.resetFields();
    },
    // 点击提交按钮触发的事件
    toSubmit() {
      // 进行表单验证
      // console.log(this.form);
      this.$refs.modelForm.validate(async (valid) => {
        if (valid) {
          // 调用保存或更新的方法，保存或更新菜品数据
          const res = await saveOrUpdate(this.sform);
          if (res.status === 200) {
            this.$message({
              type: "success",
              message: res.message,
            });
            // 重新获取数据
            this.getAllProduct();
            // 关闭模态框
            this.visible = false;
          } else {
            this.$message.error({
              message: "操作失败",
            });
          }
        } else {
          this.$message.error({
            message: "请正确输入相关数据",
          });
          return false;
        }
      });
    },
    // 下架菜品
    outLine(id) {
      this.$confirm("是否下架该菜品?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await offline({ id });
          if (res.status === 200) {
            this.$message({
              type: "success",
              message: "下架成功!",
            });
            // 重新获取数据
            this.getAllProduct();
          } else {
            this.$message.error({
              message: "下架失败!",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 上架菜品
    onLine(id) {
      this.$confirm("是否上架架该菜品?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success",
      })
        .then(async () => {
          const res = await online({ id });
          if (res.status === 200) {
            this.$message({
              type: "success",
              message: "上架成功!",
            });
            // 重新获取数据
            this.getAllProduct();
          } else {
            this.$message.error({
              message: "上架失败!",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.product {
  .header {
  }
  .center {
    width: 100%;

    img {
      width: 30px;
      height: 30px;
    }
  }
  // 三种操作的颜色
  .edit {
    color: #30b08f;
  }
  .edit:hover {
    cursor: pointer;
  }
  .outline {
    cursor: pointer;
  }
  .online {
    cursor: pointer;
  }
}
</style>
